package com.huawei.experiencereuse;

import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.GestureDescription;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Path;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.util.Log;
import android.view.Display;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.huawei.experiencereuse.localmodel.LocalModelAgent;
import com.huawei.experiencereuse.utils.ModelUtility;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;

public class ExperienceReuseService extends AccessibilityService {
    private static final String TAG = "ExperienceReuseService";
    private static final String DACHE = "DaChe";
    private static final String BOOK_HOTEL = "BookHotel";
    private static final String DACHE_INTENT = "请使用高德地图打车到%s";
    private static final String BOOK_HOTEL_INTENT = "请使用携程预定%s市%s附近的酒店";
    private static final String GAODE_MAP_PACKAGE_NAME = "com.autonavi.minimap";
    private static final String XIECHENG_TRAVEL_PACKAGE_NAME = "ctrip.android.view";
    private static final boolean EVALUATE_BY_SILICON_FLOW = false;
    private static final boolean EVALUATE_BY_IMAGE_SIMILARITY = true;

    private static int task_step = 0;
    private String intent;
    private Context context;
    private String curScreenShotFileName;
    private int width;
    private int height;
    private ImageSemanticAnalyzer analyzer;
    private boolean semanticAnalyzerRes = false;
    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (event.getEventType() != AccessibilityEvent.TYPE_VIEW_CLICKED) {
            return;
        }
        AccessibilityNodeInfo source = event.getSource();
        if (source == null) {
            return;
        }
        String buttonType = getButtonType(source);
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode == null) {
            source.recycle();
            return;
        }
        if (Objects.equals(buttonType, DACHE)) {
            String destination = getEditTextContent(rootNode, "com.huawei.experiencereuse:id/editTextDest");
            this.intent = String.format(DACHE_INTENT, destination);
            Log.e(TAG, "intent="+intent);
            Log.e(TAG, this.intent);
        } else if (Objects.equals(buttonType, BOOK_HOTEL)) {
            String city = getEditTextContent(rootNode, "com.huawei.experiencereuse:id/editTextHotelCity");
            String location = getEditTextContent(rootNode, "com.huawei.experiencereuse:id/editTextHotelLocation");
            this.intent = String.format(BOOK_HOTEL_INTENT, city, location);
            Log.e(TAG, this.intent);
        }
        this.context = getApplicationContext();
        this.analyzer = new ImageSemanticAnalyzer(this.context);
        ExperienceManager experienceManager = ExperienceManager.getInstance(this.context);
        JSONObject matchedExperience = experienceManager.getMatchedExperience(this.intent);
        String fineTunedExperience = null;
        try {
            fineTunedExperience = experienceManager.fineTuningExperience(this.intent, matchedExperience);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        executeExperience(fineTunedExperience);

        rootNode.recycle();
        source.recycle();
        this.analyzer.releaseResource();
    }

    private void executeExperience(String fineTunedExperience) {
        String desc;
        JSONObject action;
        String actionType;
        int actionId;
        String expectedImagesDir = "";
        String postCheck = "";
        getReferenceImageSize();
        try {
            JSONObject root = new JSONObject(fineTunedExperience);
            JSONArray steps = root.getJSONArray("steps");
            for (int i = 0; i < steps.length(); i++) {
                this.semanticAnalyzerRes = false;
                JSONObject step = steps.getJSONObject(i);
                desc = step.getString("desc");
                actionId = step.getInt("id");
                JSONArray actions = step.getJSONArray("actions");
                postCheck = step.getString("post_check");
                for (int j = 0; j < actions.length(); j++) {
                    action = actions.getJSONObject(j);
                    actionType = action.getString("type");
                    if (actionType.equals("click")) {
                        // 由于每台手机的应用布局不同，所以打开APP，不使用找点击绝对坐标的方式
                        if (desc.contains("打开高德地图")) {
                            Log.e(TAG, "开始打开高德APP");
                            expectedImagesDir = "dache/";
                            if (!openApp(GAODE_MAP_PACKAGE_NAME)) {
                                Toast.makeText(this, "打开高德APP失败", Toast.LENGTH_LONG).show();
                                return;
                            }
                        } else if (desc.contains("打开携程旅行")) {
                            Log.e(TAG, "开始打开携程旅行");
                            expectedImagesDir = "book_hotel/";
                            if (!openApp(XIECHENG_TRAVEL_PACKAGE_NAME)) {
                                Toast.makeText(this, "打开携程APP失败", Toast.LENGTH_LONG).show();
                                return;
                            }
                        } else {
                            Log.e(TAG, "开始处理点击事件");
                            JSONArray values = action.getJSONArray("value");
                            int x = values.getInt(0);
                            int y = values.getInt(1);

                            int xAbsolute = (int) Math.round((x / 1000.0) * this.width);
                            int yAbsolute = (int) Math.round((y / 1000.0) * this.height);
                            Log.e(TAG, "agent 开始处理点击事件，事件转换后坐标，xAbsolute: " + xAbsolute);
                            Log.e(TAG, "agent 开始处理点击事件，事件转换后坐标，yAbsolute: " + yAbsolute);
                            Point point = new Point(xAbsolute, yAbsolute);
                            AccessibilityNodeInfo rootNode = getRootInActiveWindow();
                            if (rootNode != null) {
                                Log.e(TAG, "postRequest: " + "click begin.");
                                performClick(rootNode, point);
                            }
                        }
                    } else if (actionType.equals("type")) {
                        Log.e(TAG, "开始处理输入事件");
                        String value = action.getString("value");
                        AccessibilityNodeInfo focusNode = getRootInActiveWindow().findFocus(AccessibilityNodeInfo.FOCUS_INPUT);
                        Log.e(TAG, (String) focusNode.getClassName());
                        // 检查是否是有效的输入框
                        if (focusNode != null && isInputField(focusNode)) {
                            Log.e(TAG, "开始进行输入" + value);
                            Bundle bundle = new Bundle();
                            bundle.putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, value);
                            focusNode.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, bundle);
                            focusNode.recycle();
                        }
                    } else if (actionType.equals("sleep")) {
                        int value = action.getInt("value");
                        Log.e(TAG, "睡眠"+value+"s");
                        Thread.sleep(value * 1000);
                    } else if (actionType.equals("finished")) {
                        Log.i(TAG, "检测到finish事件，当前任务已完成");
                        Toast.makeText(this, "任务完成", Toast.LENGTH_LONG).show();
                        return;
                    }
                }

                // 截图
                // 初始化计数器（1表示需要等待1个任务完成）
                CountDownLatch latch = new CountDownLatch(1);
                Thread screenShotThread = new Thread(() -> takeScreenshot(new ScreenshotSaveCallback() {
                    @Override
                    public void onSuccess(String fileName) {
                        latch.countDown(); // 截图线程结束，则计数器减1
                    }

                    @Override
                    public void onFailure(String errorMessage) {
                        latch.countDown(); // 截图线程结束，则计数器减1
                        // 考虑如何处理截图失败的情况，例如重试或通知用户
                    }
                }));
                screenShotThread.start();
                // 这里等待截图线程完成
                boolean isCompleted = latch.await(5, java.util.concurrent.TimeUnit.SECONDS);
                if (isCompleted) {
                    Log.d(TAG, "截图完成");
                    // 此处处理子线程的执行结果
                } else {
                    Log.d(TAG, "主线程：等待截图线程超时（超过5秒）");
                }

                // 监督
                if (postCheck == null || postCheck.isEmpty()) {
                    continue;
                }
                String expectedImagePath = expectedImagesDir + actionId + ".jpg";
                String screenShotFilePath = getScreenShotFilePath(this.curScreenShotFileName);
                if(EVALUATE_BY_SILICON_FLOW) {
                    // 通过硅基流动API完成监督
                    evaluateBySiliconFlow(screenShotFilePath, expectedImagePath, postCheck);
                } else {
                    // 通过本地大模型完成监督
                    Log.e(TAG, "当前截图为：" + this.curScreenShotFileName + "，参考图片为：" + actionId + ".jpg" + "，语义为：" + postCheck);
                    evaluate(screenShotFilePath, expectedImagesDir, actionId + ".jpg", postCheck);
                }
                if (!this.semanticAnalyzerRes) {
                    Log.e(TAG, "经验执行失败");
                    Toast.makeText(this, "执行经验失败", Toast.LENGTH_LONG).show();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(this, "执行经验失败", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 检查节点是否是输入框
     */
    private boolean isInputField(AccessibilityNodeInfo node) {
        // 检查类名
        String className = node.getClassName().toString();
        if (className.equals("android.widget.EditText") ||
                className.contains("EditText")) {
            return true;
        }

        // 检查是否可输入
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            if (node.isEditable()) {
                return true;
            }
        }

        // 检查输入类型
        Bundle extras = node.getExtras();
        if (extras != null && extras.containsKey("inputType")) {
            return true;
        }

        return false;
    }

    public void getReferenceImageSize() {
        AssetManager assetManager = this.context.getAssets();
        InputStream inputStream = null;

        try {
            // 打开 assets 文件流
            inputStream = assetManager.open("dache/0.jpg");

            // 创建 BitmapFactory.Options
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true; // 只解析边界信息，不加载像素

            // 解析图片
            BitmapFactory.decodeStream(inputStream, null, options);

            // 获取宽高
            this.width = options.outWidth;
            this.height = options.outHeight;

            Log.i(TAG, "图片尺寸: " + width + "x" + height);
        } catch (IOException e) {
            Log.e(TAG, "读取图片dahce/0.jpg", e);
        } finally {
            // 关闭流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    Log.e("ImageSize", "关闭流失败", e);
                }
            }
        }
    }

    private boolean openApp(String apkName) {
        Intent intent = getPackageManager().getLaunchIntentForPackage(apkName);
        if (intent == null) {
            Toast.makeText(this, "高德地图未安装", Toast.LENGTH_SHORT).show();
            return false;
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        return true;
    }

    private void evaluate(String inputImage, String referenceImageDir, String referenceImage, String description) {
        LocalModelAgent agent = LocalModelAgent.getInstance();

        if (EVALUATE_BY_IMAGE_SIMILARITY) {
            // 方式1： 通过对比两张图片相似性来评估当前的行为是否正确
            File dir = getDir("assets", Context.MODE_PRIVATE);
            File targetDir = new File(dir, "models");
            String targetDirPath = targetDir.getAbsolutePath() + File.separator;
            if (!ModelUtility.copyResourcesToAppDir(getAssets(), referenceImageDir, targetDirPath, referenceImage)) {
                Log.e(TAG, "拷贝参考图片"+referenceImage+"到"+targetDirPath+"失败");
                this.semanticAnalyzerRes = false;
                return;
            }
            this.semanticAnalyzerRes = agent.isPicSimilar(inputImage, targetDirPath + referenceImage);
        } else {
            // 方式2： 通过对比截图和描述的语义
            this.semanticAnalyzerRes = agent.isTextMatchPic(inputImage, description);
        }
    }

    private void evaluateBySiliconFlow(String screenShotFilePath, String expectedImagePath, String postCheck) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        Log.i(TAG, "开始进行语义监督");
        Thread compareThread = new Thread(() -> {
            this.analyzer.compareImageWithDescription(screenShotFilePath,
                    expectedImagePath, postCheck, new ImageSemanticAnalyzerCallback() {
                        @Override
                        public void onSuccess(boolean result) {
                            if (result) {
                                Log.i(TAG, "语义监督成功");
                                semanticAnalyzerRes = true;
                            } else {
                                Log.i(TAG, "语义监督失败");
                            }
                            latch.countDown();
                        }
                        @Override
                        public void onError(Exception e) {
                            // 主线程中显示错误
                            Log.i(TAG, "语义监督错误" + e.getMessage());
                            latch.countDown();
                        }
                    });
        });
        compareThread.start();

        boolean isCompleted = latch.await(20, java.util.concurrent.TimeUnit.SECONDS);
        if (isCompleted) {
            Log.d(TAG, "语义监督完成");
            // 此处处理子线程的执行结果
        } else {
            Log.d(TAG, "主线程：等待语义监督线程超时（超过20秒）");
        }
    }

    private String getButtonType(AccessibilityNodeInfo node) {
        String resourceName = node.getViewIdResourceName();
        if (resourceName == null) {
            return "";
        }
        if (resourceName.equals("com.huawei.experiencereuse:id/buttonDache")) {
            return DACHE;
        }
        if (resourceName.equals("com.huawei.experiencereuse:id/buttonBookHotel")) {
            return BOOK_HOTEL;
        }
        return "";
    }

    private void takeScreenshot(ScreenshotSaveCallback callback) {
        Log.d(TAG, "开始截图");
        Looper.prepare();
        Looper currentLooper = Looper.myLooper(); // 获取当前线程的Looper
        Executor currentThreadExecutor = command -> {
            new Handler(currentLooper).post(command);
        };
        takeScreenshot(Display.DEFAULT_DISPLAY,
                currentThreadExecutor,
                new TakeScreenshotCallback() {
                    @Override
                    public void onSuccess(@NonNull ScreenshotResult screenshot) {
                        Bitmap bitmap = Bitmap.wrapHardwareBuffer(screenshot.getHardwareBuffer(), null);
                        String fileName = saveImage(bitmap);
                        if (callback != null) {
                            callback.onSuccess(fileName);
                        }
                    }

                    @Override
                    public void onFailure(int errorCode) {
                        Log.e(TAG, "截图失败，错误码：" + errorCode);
                        if (callback != null) {
                            callback.onFailure(String.valueOf(errorCode));
                        }
                    }
                });
        Looper.loop();
    }

    private String saveImage(Bitmap bitmap) {
        this.curScreenShotFileName = task_step + ".jpg";
        saveBitmapToPrivateDirectory(context, bitmap, this.curScreenShotFileName);
        task_step++;
        return this.curScreenShotFileName;
    }

    private boolean saveBitmapToPrivateDirectory(Context context, Bitmap bitmap, String fileName) {
        File externalFilesDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (externalFilesDir == null) {
            externalFilesDir = context.getFilesDir();
        }

        File file = new File(externalFilesDir, fileName);
        Log.e(TAG, "saveBitmapToPrivateDirectory: " + file.getPath());
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
            fos.flush();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public void onInterrupt() {

    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        Log.i("MyAccessibility", "服务已连接"); // 若未输出，说明服务未启动
    }

    private String getEditTextContent(AccessibilityNodeInfo rootNode, String nodeName) {
        List<AccessibilityNodeInfo> editTextNodes = rootNode.findAccessibilityNodeInfosByViewId(nodeName);
        if (editTextNodes.isEmpty()) {
            return "";
        }
        AccessibilityNodeInfo editTextNode = editTextNodes.get(0);
        if (editTextNode.getText() == null) {
            editTextNode.recycle();
            return "";
        }
        String destination = editTextNode.getText().toString();
        if (destination.isEmpty()) {
            editTextNode.recycle();
            return "";
        }
        editTextNode.recycle();
        return destination;
    }

    private void performClick(AccessibilityNodeInfo rootNode, Point point) {
        GestureDescription.Builder builder = new GestureDescription.Builder();
        Path path = new Path();
        path.moveTo(point.x, point.y);
        GestureDescription.StrokeDescription strokeDescription = new GestureDescription.StrokeDescription(path, 0, 50);
        builder.addStroke(strokeDescription);
        GestureDescription gesture = builder.build();
        dispatchGesture(gesture, new GestureResultCallback() {
            @Override
            public void onCompleted(GestureDescription gestureDescription) {
                super.onCompleted(gestureDescription);
                Log.e(TAG, "点击手势完成");
                SystemClock.sleep(1000);
            }

            @Override
            public void onCancelled(GestureDescription gestureDescription) {
                super.onCancelled(gestureDescription);
                Log.e(TAG, "点击手势被取消");
            }
        }, null);
    }

    private Bitmap loadImageFromAssets(String filePath) {
        InputStream inputStream = null;
        try {
            inputStream = this.context.getAssets().open(filePath);

            // 将输入流解码为Bitmap（Android中替代BufferedImage的图像类）
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            if (bitmap != null) {
                Log.d(TAG, "成功加载预期的图片"+filePath);
            } else {
                Log.e(TAG, "图片解码失败，可能是格式不支持或文件损坏");
            }
            return bitmap;

        } catch (IOException e) {
            Log.e(TAG, "图片文件打开失败：" + e.getMessage());
            e.printStackTrace();
        } finally {
            // 关闭输入流释放资源
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private String getScreenShotFilePath(String fileName) {
        // 1. 获取应用外部存储私有目录的Pictures子目录
        File picturesDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (picturesDir == null) {
            Log.e(TAG, "无法获取Pictures目录，可能外部存储不可用");
            return null;
        }

        // 2. 构建图片文件完整路径
        File imageFile = new File(picturesDir, fileName);
        Log.d(TAG, "图片路径：" + imageFile.getAbsolutePath());

        // 3. 检查文件是否存在
        if (!imageFile.exists() || !imageFile.isFile()) {
            Log.e(TAG, "图片文件不存在：" + imageFile.getAbsolutePath());
            return null;
        }

        return imageFile.getPath();
    }
}
